package cangyan.msgcenter.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class DateUtil {

	//24小时过期时间
	public static final long OVER_DUE_TIME = 24*60*60*1000;
	
	// 72小时过期时间
	public static final long OVER_DUE_TIME_SP = 72*60*60*1000;
	
	public static final String FMT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
	
	public static final String FMT_DATE = "yyyy-MM-dd";
	
	public static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
	
	
	/**
	 * 获取当前时间的前n个月或者后n个月
	 * @param format 返回格式
	 * @param n  月数
	 * @param flag 1 表示当前时间前,2表示当前时间后
	 * @return
	 */
	public static String getBeforDate(String format,int n,int flag){
		
		if(StringUtils.isBlank(format)){
			format = FMT_DATE;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime( new Date());
		calendar.set(Calendar.DATE,1);
		
		if(1 == flag){
			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)-n);
		}else {
			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)+n);
		}
		return formatDate(calendar, format);
		
	}
	
	/**
	 * 获取系统当前日期时间(格式自定)
	 * 
	 * @param format
	 *            返回日期的格式 默认为 yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String getFormatDate(String format) {
		return formatDate(new Date(), format);
	}

	/**
	 * yyyy-MM-dd HH:mm:ss.
	 * @return
	 */
	public static String getFormatDate() {
		return formatDate(new Date(),FMT_DATE_TIME);
	}
	
	/**
	 * 获取当前日期的前n天或后n天的时间
	 * 
	 * @param i
	 *            天数
	 * @param flag
	 *            1表示后N天 2表示前N天
	 * @param format
	 *            返回日期的格式 默认为 yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String getOtherDaytime(int i, String flag, String format) {
		Calendar cal = Calendar.getInstance();
		if ("1".equals(flag)) {
			cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + i);
		} else {
			cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - i);
		}
        return formatDate(cal, format);
	}
	
	/**
	 * 验证当前月份是否在当前X个月以内
	 * @param month
	 * @return
	 */
	public static boolean checkMonth(int month, int scope){
		Date date = new Date();
		DateFormat df = new SimpleDateFormat("MM");
		int nowmonth = Integer.parseInt(df.format(date));
		//int nowmonth = 5;
		int i = scope-1;
		if( month <1 || month >12){
			return false;
		}else{
			if( nowmonth >i){
				if(month > nowmonth || month < nowmonth -i){
					return false;
				}else{
					return true;
				}
			}else{
				if(month < nowmonth || (month > nowmonth + (12-scope) && month <= 12)){
					return true;
				}else{
					return false;
				}
			}
		}
	}
	
	/**
	 * 获取当前日期前N个月份列表
	 * @param scope
	 * @return
	 */
	public List getMonthlist(int scope){
		List list = new ArrayList();
		for (int i = 1; i <= scope; i++) {			
			HashMap map = new HashMap();
			
			String startdate = getBeforDate("yyyyMMdd",i,1);
			String enddate = getBeforDate("yyyyMMdd", i-1,1);
			String name = startdate.substring(0, 4)+"年"+startdate.substring(4, 6);
			
			map.put("startdate", startdate);
			map.put("enddate", enddate);
			map.put("name", name);
			
			list.add(map);		
			
		}
		return list;
	}
	
	
	/**
	 * 获取当前月份MM
	 * @return
	 */
	public static String getMonth(){
		return formatDate(new Date(), "MM");
	}
	
	/**
	 * 获取当前小时
	 * @return
	 */
	public static String getHour(){
		return formatDate(new Date(), "HH");
	}
	
	/**
	 * 获取当前年份yyyy
	 * @return
	 */
	public static String getYear(){
		return formatDate(new Date(), "yyyy");
	}
	
	/**
	 * 获取当前日期dd
	 * @return
	 */
	public static String getDate(){
		return formatDate(new Date(), "dd");
	}
	
	/**
	 * 判断指定的日期是否已过期
	 * @param checkedDate
	 * @return
	 */
	public static boolean isOverdue(Date checkedDate, long milliseconds) {
		Calendar cd = Calendar.getInstance();
		Date now = cd.getTime();
		// 时间往前移多少毫秒
		now.setTime(now.getTime()-milliseconds);
		return checkedDate.before(now);
	}
	
	/**
	 * 判断指定的日期是否已过期
	 * @param checkedDate
	 * @return
	 */
	public static boolean isOverdue(String indate,String format, long milliseconds) {
		Date date = parseDate(indate, format);
		return isOverdue(date,milliseconds);
	}
	
	
	/**
	 * 解析格式字符串为时间戳
	 * @param src
	 * @param fmt
	 * @return
	 */
	public static Timestamp parseToTimestamp(String src, String fmt) {
		java.text.Format f = new java.text.SimpleDateFormat(fmt);
		try {
			Date date = (Date) f.parseObject(src);
			return new Timestamp(date.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return new Timestamp(new Date().getTime());
	}
	
	/**
	 * 
	 * @param date
	 * @param begin
	 * @param end
	 * @return
	 */
	public static boolean isDateInRange(Date date, String begin, String end) {
		
		if (date.before(parseToTimestamp(end, FMT_DATE)) && date.after(parseToTimestamp(begin, FMT_DATE))) {
			return true;
		} else {
			return false;
		}
	}
	
	
	/**
	 * 将日期转化为中文形式
	 * @param numdate
	 * @return
	 */
	public static String changeNumDateToCHNdate(String numdate,String format){
		String chndate = "";
		if(numdate != null && !"".equals(numdate)){
			if ("yyyyMM".equals(format)) {
				chndate = numdate.substring(0,4)+"年"+numdate.substring(4,6)+"月";
			}else if ("yyyyMMdd".equals(format)) {
				chndate = numdate.substring(0,4)+"年"+numdate.substring(4,6)+"月"+numdate.substring(6, 8)+"日";
			}
			
		}
		return chndate;
	}
	
	/**
	 * 将指定字符串格式的时间串转化为需要的格式时间串
	 * @param numdate
	 * @return
	 */
	public static String changeNumDateToDate(String numdate,String inFormat,String outFormat){
		return parseDate(numdate, inFormat, outFormat);
	}
	
	/**
	 * 获取每个月的第一天
	 * @param nowdate
	 * @param inFormat
	 * @param outFormat
	 * @return
	 */
	public static String getFistDay(String nowdate,String inFormat,String outFormat){
		Calendar cl = parseCalendar(nowdate, inFormat);
		cl.set(Calendar.DAY_OF_MONTH, 1);	
		return formatDate(cl,outFormat);
	}
	
	/**
	 * 获取后一个月的第一天
	 * @param nowdate
	 * @param inFormat
	 * @param outFormat
	 * @return
	 */
	public static String getNextMonthFistDay(String nowdate,String inFormat,String outFormat){
		Calendar cl = parseCalendar(nowdate, inFormat);
		cl.set(Calendar.MONTH, cl.get(Calendar.MONTH)+1);
		cl.set(Calendar.DAY_OF_MONTH, 1);	
		return formatDate(cl, outFormat);
	}
	
	/**
	 * 获取一个月的最后一天
	 * @param nowdate
	 * @param inFormat
	 * @param outFormat
	 * @return
	 */
	public static String getLastDay(String nowdate,String inFormat,String outFormat){
		Date date = parseDate(nowdate, inFormat);
		Calendar cl = Calendar.getInstance();
		cl.setTime(date);
		cl.set(Calendar.DAY_OF_MONTH, cl.getActualMaximum(Calendar.DAY_OF_MONTH)); 
	    return formatDate(cl, outFormat);
	}
	
	
	
	/**
	 * 详细设计： 1.被400整除是闰年，否则： 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
	 * 3.能被4整除同时能被100整除则不是闰年
	 */
	public static boolean isLeapYear(int year) {
		if ((year % 400) == 0){
			return true;
		}
		if((year % 4) == 0) {
			if ((year % 100) == 0){
				return false;
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 判断当前时间是否在时间区间内
	 * @return
	 */
	public static boolean checkBetweenDate(String begindate,String enddate,String format){
		boolean flag = false;
		Calendar cd = Calendar.getInstance();
		Date nowdate = cd.getTime();
		DateFormat df = new SimpleDateFormat(format);
		try {
			flag = nowdate.after(df.parse(begindate));
			if (flag) {
				flag = nowdate.before(df.parse(enddate));
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return !flag;
	}
	
	/**
	 * 格式化Date,默认格式yyyy-MM-dd HH:mm:ss.
	 * @param date null为当前日期
	 * @param format 空默认为yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String formatDate(Date date, String format) {
		if (date == null) {
			date = new Date();
		}
		if(StringUtils.isBlank(format)){
			format = FMT_DATE_TIME;
		}
		DateFormat df = new SimpleDateFormat(format);
		return df.format(date);
	}
	
	/**
	 * 默认yyyy-MM-dd HH:mm:ss.
	 * @param cal
	 * @param format
	 * @return
	 */
	public static String formatDate(Calendar cal, String format) {
		return formatDate(cal.getTime(), format);
	}
	
	/**
	 * yyyy-MM-dd HH:mm:ss.
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {
		return formatDate(date, null);
	}
	
	
    /**
     * 字符串日期转换为Date
     * @param date
     * @param format
     * @return
     */
    public static Date getDate(String date, String format) {
    	SimpleDateFormat haifnformat = new SimpleDateFormat(format);
        Date dt = null;
        try {
            dt = haifnformat.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dt;
    }
    /**
     * 字符串日期转换为Date
     * @param date
     * @param format
     * @return
     */
    public static Date getDate(String date) {
        return getDate(date,FMT_DATE_TIME);
    }
    
    /**
     * 判断是否是时间
     * @param date
     * @param format
     * @return
     */
    public static boolean isDate(String date, String format) {
        boolean flag = false;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            date = date.replace("/", "-");
            //指定日期/时间解析是否不严格
            sdf.setLenient(false);
            sdf.parse(date);
            flag = true;
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }
    
    /**
     * @param date 空为当天
     * @param inFormat 默认 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date parseDate(String date,String inFormat){
    	if(StringUtils.isBlank(inFormat)){
    		inFormat = FMT_DATE_TIME;
    	}
    	if(StringUtils.isBlank(date)){
    		date = formatDate(new Date(),inFormat);
    	}
    	try {
    		SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
			return sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    
    /**
     * @param date 空为当天
     * @param inFormat 默认 yyyy-MM-dd HH:mm:ss
     * @param outFormat 默认 yyyy-MM-dd HH:mm:ss 
     * @return
     */
    public static String parseDate(String date,String inFormat,String outFormat){
    	if(StringUtils.isBlank(outFormat)){
    		outFormat = FMT_DATE_TIME;
    	}
    	return formatDate(parseDate(date, inFormat), outFormat);
    }
    
    public static Calendar parseCalendar(String date,String inFormat){
    	Calendar cal = Calendar.getInstance();
    	Date d = parseDate(date, inFormat);
    	cal.setTime(d);
    	return cal;
    }
    
    /**
     * 是否小于今天23：59：59
     * @param date
     * @return
     */
    public static boolean isLtToday(Date date){
    	if(date == null){
    		return false;
    	}
    	Calendar cal = Calendar.getInstance();
    	cal.set(Calendar.HOUR_OF_DAY, 23);
    	cal.set(Calendar.MINUTE, 59);
    	cal.set(Calendar.SECOND, 59);
    	Long d = date.getTime();
    	Long t = cal.getTimeInMillis();
    	if(d<t){
    		return true;
    	}
    	return false;
    }
    
    /**
     * 是否小于今天
     * @param date yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static boolean isLtToday(String date){
    	if(StringUtils.isBlank(date)){
    		return false;
    	}
    	return isLtToday(getDate(date));
    }
}
